package qingma

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc/status"
	"qm_system_server/server/global"
	"qm_system_server/server/model/common/response"
	"qm_system_server/server/proto/grpc/rpc"
	"qm_system_server/server/utils"
	"strconv"
)

type RpcApi struct {
}

func (r *RpcApi) GetRpc(c *gin.Context) {
	// 获取查询参数
	query := c.Request.URL.Query()

	// 转换查询参数为map[string]string
	queryParams := make(map[string]interface{})
	queryParams["userId"] = utils.GetUserID(c)
	fmt.Println(queryParams["userId"])
	queryParams["gameHash"] = c.Request.Header.Get("game-hash")
	var platformId string
	platformId = c.Request.Header.Get("platform-id")
	queryParams["platformId"], _ = strconv.ParseInt(platformId, 10, 64)

	for key, values := range query {
		// 这里我们假设每个键只有一个值，所以取第一个
		if len(values) > 0 {
			queryParams[key] = values[0]
		}
	}

	queryJson, _ := json.Marshal(queryParams)
	grpcClient := rpc.NewRpcServiceClient(global.OperateGrpc)
	resp, err := grpcClient.Get(c, &rpc.GetRequest{
		Server:    queryParams["server"].(string),
		QueryJson: string(queryJson),
	})
	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			// 获取 gRPC 错误的描述信息
			response.FailWithMessage(st.Message(), c)
		}
		return
	}
	var data interface{}
	json.Unmarshal([]byte(resp.Result), &data)

	response.Result(0, data, "success", c)
}

func (r *RpcApi) PostRpc(c *gin.Context) {
	// 定义一个 map 来存放 POST 请求中的参数
	queryParams := make(map[string]interface{})

	// 获取 userId 和其他 Header 参数
	queryParams["userId"] = utils.GetUserID(c)
	queryParams["gameHash"] = c.Request.Header.Get("game-hash")

	// 处理 platformId
	var platformId string
	platformId = c.Request.Header.Get("platform-id")
	queryParams["platformId"], _ = strconv.ParseInt(platformId, 10, 64)

	if err := c.ShouldBindJSON(&queryParams); err != nil {
		response.FailWithMessage("Invalid JSON format:"+err.Error(), c)
		return
	}

	// 将参数转换为 JSON 字符串
	queryJson, _ := json.Marshal(queryParams)

	// 调用 gRPC 服务
	grpcClient := rpc.NewRpcServiceClient(global.OperateGrpc)
	resp, err := grpcClient.Get(c, &rpc.GetRequest{
		Server:    queryParams["server"].(string),
		QueryJson: string(queryJson),
	})
	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			response.FailWithMessage(st.Message(), c)
		}
		return
	}

	fmt.Println(resp)
	// 解析返回结果
	var data interface{}
	json.Unmarshal([]byte(resp.Result), &data)

	response.OkWithData(data, c)
}
